package com.example.demo.controllers.manage;

import com.example.demo.exception.BusinessException;
import com.example.demo.model.dto.PaperSubmissionDTO;
import com.example.demo.model.entity.achievement.ResearchPaper;
import com.example.demo.model.entity.audit.AuditRecord;
import com.example.demo.service.PaperService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/student/papers")
@RequiredArgsConstructor
@Slf4j
@SecurityRequirement(name = "bearerAuth")
@Tag(name = "学生论文管理", description = "学生论文提交、修改、删除和查看接口")
public class StudentManageController {

    private final PaperService paperService;

    @PostMapping
    @Operation(summary = "提交论文",
            description = "学生提交科研论文",
            responses = {
                    @ApiResponse(responseCode = "200", description = "提交成功",
                            content = @Content(schema = @Schema(implementation = ResearchPaper.class))),
                    @ApiResponse(responseCode = "400", description = "参数校验失败"),
                    @ApiResponse(responseCode = "401", description = "未认证"),
                    @ApiResponse(responseCode = "409", description = "论文已存在")
            })
    public ResponseEntity<?> submitPaper(@Valid @RequestBody PaperSubmissionDTO submissionDTO) {
        try {
            log.info("论文提交请求: 标题[{}], 期刊[{}]", submissionDTO.getPaperTitle(), submissionDTO.getJournal());
            ResearchPaper paper = paperService.submitPaper(submissionDTO);
            return ResponseEntity.ok(paper);
        } catch (BusinessException e) {
            log.warn("论文提交业务异常: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
        } catch (Exception e) {
            log.error("论文提交系统错误", e);
            return ResponseEntity.internalServerError().body("系统处理失败");
        }
    }

    @PutMapping("update/{paperId}")
    @Operation(summary = "修改论文",
            description = "学生修改论文信息（仅限草稿或需修改状态）",
            responses = {
                    @ApiResponse(responseCode = "200", description = "修改成功"),
                    @ApiResponse(responseCode = "403", description = "无权修改"),
                    @ApiResponse(responseCode = "404", description = "论文不存在")
            })
    public ResponseEntity<?> updatePaper(
            @PathVariable Long paperId,
            @Valid @RequestBody PaperSubmissionDTO updateDTO) {
        try {
            ResearchPaper paper = paperService.updateStudentPaper(paperId, updateDTO);
            return ResponseEntity.ok(paper);
        } catch (BusinessException e) {
            log.warn("论文修改失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @DeleteMapping("delete/{paperId}")
    @Operation(summary = "删除论文",
            description = "学生删除论文（仅限草稿状态）",
            responses = {
                    @ApiResponse(responseCode = "204", description = "删除成功"),
                    @ApiResponse(responseCode = "403", description = "无权删除")
            })
    public ResponseEntity<Void> deletePaper(@PathVariable Long paperId) {
        try {
            paperService.deleteStudentPaper(paperId);
            return ResponseEntity.noContent().build();
        } catch (BusinessException e) {
            log.warn("论文删除失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
    }

    @GetMapping("get")
    @Operation(summary = "获取我的论文列表",
            description = "获取当前学生提交的所有论文（按提交时间降序）",
            responses = {
                    @ApiResponse(responseCode = "200", description = "获取成功",
                            content = @Content(schema = @Schema(implementation = ResearchPaper[].class)))
            })
    public ResponseEntity<List<ResearchPaper>> getMyPapers() {
        List<ResearchPaper> papers = paperService.getStudentPapers();
        log.info("获取论文列表，共{}篇", papers.size());
        return ResponseEntity.ok(papers);
    }

    @GetMapping("getPaper/{paperId}")
    @Operation(summary = "获取论文详情",
            description = "获取指定论文的详细信息",
            responses = {
                    @ApiResponse(responseCode = "200", description = "获取成功"),
                    @ApiResponse(responseCode = "404", description = "论文不存在")
            })
    public ResponseEntity<?> getPaperDetails(@PathVariable Long paperId) {
        try {
            ResearchPaper paper = paperService.getStudentPaperById(paperId);
            return ResponseEntity.ok(paper);
        } catch (BusinessException e) {
            log.warn("论文查询失败: {}", e.getMessage());
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/pending-review")
    @Operation(summary = "获取待审核论文",
            description = "获取所有待审核的论文（按提交时间升序）",
            responses = {
                    @ApiResponse(responseCode = "200", description = "获取成功",
                            content = @Content(schema = @Schema(implementation = ResearchPaper[].class)))
            })
    public ResponseEntity<List<ResearchPaper>> getPendingReviewPapers() {
        List<ResearchPaper> papers = paperService.getPendingReviewPapers();
        log.info("获取待审核论文，共{}篇", papers.size());
        return ResponseEntity.ok(papers);
    }

    @GetMapping("audit-records/{paperId}")
    @Operation(summary = "获取论文审核记录",
            description = "获取指定论文的审核记录",
            responses = {
                    @ApiResponse(responseCode = "200", description = "获取成功",
                            content = @Content(schema = @Schema(implementation = AuditRecord[].class))),
                    @ApiResponse(responseCode = "404", description = "论文不存在")
            })
    public ResponseEntity<List<AuditRecord>> getPaperAuditRecords(@PathVariable Long paperId) {
        try {
            List<AuditRecord> auditRecords = paperService.getPaperAuditRecords(paperId);
            return ResponseEntity.ok(auditRecords);
        } catch (BusinessException e) {
            log.warn("获取论文审核记录失败: {}", e.getMessage());
            return ResponseEntity.notFound().build();
        }
    }
}